<!-- 保养列表 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    <template #buts>
      <a-button
        type="primary"
        @click="
          () => {
            type = 6;
            unkeepVisible = true;
          }
        "
      >
        <template #icon>
          <icon-plus></icon-plus>
        </template>
        <template #default>设备保养</template>
      </a-button>
    </template>
  </pageHeader>
  <div class="content">
    <div class="content-header">
      <a-space>
        <div>
          <a-input-group>
            <a-select
              :style="{
                flex: 1,
              }"
              placeholder="请选择"
              v-model="currSelectName"
              @change="search"
            >
              <a-option value="number">保养单号</a-option>
              <a-option value="equipNumber">设备编码</a-option>
            </a-select>
            <a-input-search
              search-button
              :style="{
                flex: 3,
              }"
              placeholder="请输入"
              v-model="currNumber"
              @search="search"
            >
            </a-input-search>
          </a-input-group>
        </div>
        <div>
          <!-- <span> 设备名称： </span> -->
          <a-input-search
            search-button
            :style="{ width: 'auto' }"
            placeholder="请输入"
            v-model="currEquipName"
            @search="search"
          >
            <template #prefix>设备名称：</template>
            <template #button-icon>
              <icon-search />
            </template>
          </a-input-search>
        </div>
        <div>
          <!-- <span> 维修状态： </span> -->
          <div>
            <a-select
              placeholder="请选择"
              v-model="currMaintainState"
              @change="search"
            >
              <template #prefix>保养状态：</template>
              <a-option :value="0">全部</a-option>
              <a-option :value="1">待派工</a-option>
              <a-option :value="2">待保养</a-option>
              <a-option :value="3">进行中</a-option>
              <a-option :value="4">已保养</a-option>
            </a-select>
          </div>
        </div>
        <a-button type="primary" @click="search">
          <template #icon>
            <icon-search />
          </template>
          <template #default>搜索</template>
        </a-button>
        <a-button type="outline" @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          <template #default>重置</template>
        </a-button>
      </a-space>
      <a-space>
        <!-- <a-button type="outline">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>
        <a-button type="outline">
          <template #icon>
            <icon-export :rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button> -->
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>
        <a-button status="warning" @click="getDemandDeriveData">
          <template #icon>
            <icon-upload />
          </template>
          <template #default>导出</template>
        </a-button>
        <a-button type="primary" @click="open"> 保养派工 </a-button>
      </a-space>
    </div>
    <!-- <a-divider /> -->
    <div
      :style="{
        cursor: 'pointer',
      }"
      @click="goWaitList"
    >
      <div
        :style="{
          marginTop: '10px',
        }"
      >
        <a-alert banner type="warning"
          >设备保养提醒：有
          <span
            :style="{
              color: '#ef8432',
            }"
            >{{ waitMaintainCount }}</span
          >
          台设备需要派工保养，请尽快处理！</a-alert
        >
      </div>
    </div>
    <a-divider />
    <div>
      <TableTurn :args="args" :table-data="getData" ref="tableRef">
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>

        <a-table-column
          :width="150"
          align="center"
          title="保养单号"
          data-index="number"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
        </a-table-column>

        <a-table-column
          :width="150"
          align="center"
          title="设备名称"
          data-index="equipName"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
        </a-table-column>
        <a-table-column
          :width="150"
          align="center"
          title="设备编码"
          data-index="equipNumber"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
        </a-table-column>
        <!-- <a-table-column :width="150" align="center" title="故障描述">
          <template #cell="{ record }">
            <a-button type="text" @click="goDetail(record, 2)">查看</a-button>
          </template>
        </a-table-column> -->

        <a-table-column
          :width="150"
          align="center"
          title="保养周期"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
          <template #cell="{ record }">
            {{ `${record.maintenanceCycleNum}${record.maintenanceCycleUnit}` }}
          </template>
        </a-table-column>
        <a-table-column
          :width="150"
          align="center"
          title="保养到期预警"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
          <template #cell="{ record }">
            {{ `${record.maintenanceWarning}${record.maintenanceCycleUnit}` }}
          </template>
        </a-table-column>
        <a-table-column
          :width="150"
          align="center"
          title="保养人员"
          data-index="maintenancePeopleName"
        >
        </a-table-column>
        <a-table-column
          :width="200"
          align="center"
          title="保养开始时间"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
          <template #cell="{ record }">
            {{
              record.maintenanceStartTime === 0
                ? '-'
                : `${dayjs(record.maintenanceStartTime).format(
                    'YYYY-MM-DD HH:mm:ss'
                  )}`
            }}
          </template>
        </a-table-column>
        <a-table-column
          :width="200"
          align="center"
          title="保养结束时间"
          :ellipsis="true"
          :tooltip="{
            position: 'top',
          }"
        >
          <template #cell="{ record }">
            {{
              record.maintenanceEndTime === 0
                ? '-'
                : `${dayjs(record.maintenanceEndTime).format(
                    'YYYY-MM-DD HH:mm:ss'
                  )}`
            }}
          </template>
        </a-table-column>
        <a-table-column :width="150" align="center" title="是否需要维修">
          <template #cell="{ record }">
            {{ record.isNeedRepair ? '是' : '否' }}
          </template>
        </a-table-column>
        <a-table-column
          :width="150"
          align="center"
          title="保养状态"
          fixed="right"
        >
          <template #cell="{ record }">
            <div
              class="status"
              :style="{
                color: orderStatus.filter(
                  (ele) => ele.id === record.maintainState
                )[0]?.backgroundColor,
              }"
            >
              <p
                :style="{
                  'background': orderStatus.filter(
                    (ele) => ele.id === record.maintainState
                  )[0]?.backgroundColor,
                  'box-shadow': `0px 0px 5px`,
                }"
              ></p>
              {{
                orderStatus.filter((ele) => ele.id === record.maintainState)[0]
                  ?.value
              }}
            </div>
            <!-- <div class="repair-state">
              <div
                class="cycle"
                :class="
                  record.maintainState === 1
                    ? 'waitJob-cycle'
                    : record.maintainState === 2
                    ? 'waitRepair-cycle'
                    : record.maintainState === 3
                    ? 'running-cycle'
                    : 'finish-cycle'
                "
              >
              </div>
              <div
                :class="
                  record.maintainState === 1
                    ? 'waitJob'
                    : record.maintainState === 2
                    ? 'waitRepair'
                    : record.maintainState === 3
                    ? 'running'
                    : 'finish'
                "
                >{{
                  record.maintainState === 1
                    ? '待派工'
                    : record.maintainState === 2
                    ? '待保养'
                    : record.maintainState === 3
                    ? '进行中'
                    : '已保养'
                }}</div
              >
            </div> -->
          </template>
        </a-table-column>
        <!-- 操作item -->
        <a-table-column align="center" :width="150" fixed="right" title="操作">
          <template #cell="{ record }">
            <!-- <a-button
              type="text"
              :style="{
                backgroundColor: '#31C27C',
                color: '#fff'
              }"
              v-if="
                record.maintainState === 1 &&
                record.maintenancePeopleId == userId
              "
              @click="goDetail(record, 7)"
              >派工
            </a-button> -->

            <a-tooltip
              v-if="
                record.maintainState === 2 &&
                record.maintenancePeopleId == userId
              "
              content="保养"
            >
              <IconFont
                type="icon-baoyangguanli"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="goDetail(record, 8)"
              />
            </a-tooltip>

            <!-- <a-button
              type="text"
              :style="{
                backgroundColor: '#31C27C',
                color: '#fff',
              }"
              v-if="
                record.maintainState === 3 &&
                record.maintenancePeopleId == userId
              "
              @click="goDetail(record, 10)"
              >保养完成
            </a-button> -->

            <a-tooltip
              v-if="
                record.maintainState === 3 &&
                record.maintenancePeopleId == userId
              "
              content="保养完成"
            >
              <IconFont
                type="icon-wancheng"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="goDetail(record, 10)"
              />
            </a-tooltip>

            <a-tooltip content="保养详情">
              <IconFont
                type="icon-details-def"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="goDetail(record, 9)"
              />
            </a-tooltip>
            <a-tooltip content="删除">
              <a-popconfirm
                content="确认删除？"
                type="error"
                @ok="deleteItem(record.id)"
              >
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </template>
        </a-table-column>
      </TableTurn>
      <equipmentRepair
        :type="type"
        :form="form.list"
        v-model:visible="unkeepVisible"
        @equipmentEmit="equipmentEmit"
      ></equipmentRepair>
    </div>
  </div>
  <personnelModel
    :title="'请选择执行维修人员'"
    @personnelId="changePersonnelId"
    v-model:personnelVisible="personnelVisible"
  />
</template>

<script lang="ts" setup>
  import { useRouter } from 'vue-router';
  import { reactive, ref } from 'vue';
  import dayjs from 'dayjs';
  import {
    GetMaintenanceEquipment,
    GetMaintenanceEquipmentMain,
    PutMaintenanceEquipment,
    PostMaintenanceEquipment,
    DelMaintenanceEquipment,
  } from '@/api/equipment-management/equipment-maintain-manager';
  import { PutEquipment } from '@/api/equipment-management/equipment-list';
  import { Message } from '@arco-design/web-vue';
  import equipmentRepair from '../../components/equipment-repair/index.vue';

  const router = useRouter();
  const title: string = '设备保养列表';
  const breadCrumb: string[] = ['设备管理', '设备维护（管理）', '设备保养列表'];
  const personnelVisible = ref(false);
  // 表格配置
  const args = reactive({
    stripe: true,
    bordered: {
      headerCell: true,
    },
    rowSelection: {
      type: 'checkbox',
    },
  });

  const orderStatus = [
    { id: 1, value: '待派工', backgroundColor: '#cccccc' },
    { id: 2, value: '待保养', backgroundColor: '#009933' },
    { id: 3, value: '进行中', backgroundColor: '#4e8bfb' },
    { id: 4, value: '已保养', backgroundColor: '#009933' },
  ];
  let tableRef = ref(); // 储存table的ref
  const userId = sessionStorage.getItem('userId');
  const changePersonnelId = async (e: { id: number; name: string }) => {
    //
    try {
      // if (
      //   !tableRef.value.selectedKeys ||
      //   tableRef.value.selectedKeys.length === 0
      // )
      //   throw new Error('请选择维修的数据');
      // tableRef.value.selectedList.forEach((ele: any) => {
      //   if (ele.maintainState !== 1) {
      //     throw new Error('请选择正确的数据');
      //   }
      // });
      for (const ele of tableRef.value.selectedKeys) {
        // eslint-disable-next-line no-await-in-loop
        await PutMaintenanceEquipment({
          id: ele,
          maintenancePeopleId: e.id,
          maintenancePeopleName: e.name,
          maintainState: 2,
        });
      }
      for (const ele of tableRef.value.selectedList) {
        // eslint-disable-next-line no-await-in-loop
        await PutEquipment({
          id: ele.equipmentId,
          useState: 5,
        });
      }
      tableRef.value.selectedKeys = [];
      tableRef.value.loadData();
    } catch (error) {
      Message.error(`${error}`);
    }
  };
  const form = reactive({
    list: {
      isChangeParts: false,
      isNeedRepair: false,
      equipmentMaintainPlan: {
        maintenanceCycleUnit: null,
        maintenanceCycleNum: null,
        maintenanceWarning: null,
        planName: '',
        planContent: '',
      },
    },
  });
  let type = ref(1); // 判断弹出框的type
  let currNumber = ref(''); // 第一个搜索框
  let currSelectName = ref(''); // 储存第一个搜索框的下拉框值
  let currEquipName = ref(''); // 设备名称搜索框
  let currMaintainState = ref(undefined);
  const goWaitList = () => {
    router.push({
      name: 'UpkeepWaitList',
    });
  };
  // 搜索框事件
  const search = () => {
    tableRef.value.loadData();
  };
  // 监听键盘回车，按了回车也会查询
  const keyDown = (e: any) => {
    if (e.keyCode === 13) {
      tableRef.value.loadData();
    }
  };
  let waitMaintainCount = ref(0); // 储存待派工状态的数量
  const waitMaintainCountFn = async () => {
    try {
      const { content }: any = await GetMaintenanceEquipment({
        page: 0,
        size: -1,
        maintainState: 1,
      });
      // 获取横幅的数据，待派工状态
      waitMaintainCount.value = content.length;
      window.addEventListener('keydown', keyDown);
    } catch (error: unknown) {
      console.log(error);
    }
  };
  let unkeepVisible = ref(false); // 判断是否显示弹出框
  // 前往派工或者详情页面
  const goDetail = async (record: any, currType: number) => {
    const res = await GetMaintenanceEquipmentMain({ id: record.id });
    if (currType === 10) {
      await PutMaintenanceEquipment({
        id: record.id,
        maintainState: 4,
      });
      await PutEquipment({
        id: record.equipmentId,
        useState: 1,
      });
      unkeepVisible.value = false;
      tableRef.value.loadData();
      return;
    }
    if (!res.isChangeParts) {
      res.isChangeParts = false;
    }
    if (!res.isNeedRepair) {
      res.isNeedRepair = false;
    }

    type.value = currType;
    form.list = record;
    unkeepVisible.value = true;
  };
  // 删除
  const deleteItem = async (id: number) => {
    try {
      await DelMaintenanceEquipment({ id });
      tableRef.value.loadData();
    } catch (error: unknown) {
      console.log(error);
    }
  };
  // 获取表格数据
  const getData = async (pageData?: any) => {
    try {
      waitMaintainCountFn();
      const data: any = {};
      if (currNumber.value.trim() !== '')
        data[currSelectName.value] = currNumber.value;
      if (currEquipName.value.trim() !== '')
        data.equipName = currEquipName.value;
      if (currMaintainState.value !== undefined)
        data.maintainState = currMaintainState.value;
      else if (currMaintainState.value === 0) data.maintainState = '';
      const res: any = await GetMaintenanceEquipment({
        ...pageData,
        ...data,
      });
      // // 将保养周期的数据转成json格式
      // for (let i of res.content) {
      //   i.cycle = JSON.parse(i.cycle);
      // }
      return Promise.resolve(res);
    } catch (error: unknown) {
      console.log(error);
    }
  };
  // 弹出框的自定义事件
  const equipmentEmit = async (list: any, type: number) => {
    try {
      if (type === 8) {
        await PutMaintenanceEquipment({
          id: list.id,
          maintainState: 3,
        });
        await PutEquipment({
          id: list.equipmentId,
          useState: 6,
        });
        unkeepVisible.value = false;
        tableRef.value.loadData();
        return;
      }
      if (type === 6) {
        const {
          equipmentId,
          actualMaintenanceContent,
          actualMaintenanceMeasure,
        } = list;
        await PostMaintenanceEquipment({
          equipmentId,
          actualMaintenanceContent,
          actualMaintenanceMeasure,
        });
        unkeepVisible.value = false;
        tableRef.value.loadData();
      }
      if (type === 7 || type === 8) {
        const {
          id,
          maintainState,
          actualMaintenanceContent,
          actualMaintenanceMeasure,
          maintenancePeopleName,
          maintenancePeopleId,
          maintenanceStartTime,
          maintenanceEndTime,
          isChangeParts,
          isNeedRepair,
        } = list;

        await PutMaintenanceEquipment({
          id,
          maintainState: type === 8 ? 3 : maintainState,
          actualMaintenanceContent,
          actualMaintenanceMeasure,
          maintenancePeopleName,
          maintenancePeopleId,
          maintenanceStartTime: +maintenanceStartTime,
          maintenanceEndTime: +maintenanceEndTime,
          isChangeParts,
          isNeedRepair,
        });
        unkeepVisible.value = false;
        tableRef.value.loadData();
      }
      if (type === 9) {
        await PutMaintenanceEquipment(list);
        unkeepVisible.value = false;
        tableRef.value.loadData();
      }
    } catch (error: unknown) {
      console.log(error);
    }
  };
  const open = () => {
    try {
      if (
        !tableRef.value.selectedKeys ||
        tableRef.value.selectedKeys.length === 0
      )
        throw new Error('请选择维修的数据');
      tableRef.value.selectedList.forEach((ele: any) => {
        if (ele.maintainState !== 1) {
          throw new Error('请选择正确的数据');
        }
      });
      personnelVisible.value = true;
    } catch (error) {
      console.log(error);
      Message.error(`${error}`);
    }
  };
  // 重置
  const reset = () => {
    currNumber.value = '';
    currSelectName.value = '';
    currEquipName.value = '';
    currMaintainState.value = undefined;
    tableRef.value.loadData();
  };
</script>

<style scoped lang="less">
  .content {
    padding: 10px;

    &-header {
      display: flex;
      width: 100%;
      height: 40px;
      justify-content: space-between;
    }
    .status {
      display: flex;
      align-items: center;
      justify-content: center;

      p {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        margin-right: 10px;
      }
    }
  }
</style>
